package top.heue.test.app

import android.content.Context
import android.content.Intent
import androidx.multidex.MultiDexApplication
import com.github.anrwatchdog.ANRWatchDog
import com.hjq.permissions.XXPermissions
import com.orhanobut.hawk.Hawk
import top.heue.test.activity.container.ContainerActivity
import top.heue.test.activity.error.ErrorActivity
import top.heue.test.http.Http
import top.heue.utils.FC
import top.heue.utils.base.util.system.SystemUtil
import top.heue.utils.log.L
import top.heue.utils.log.L.string


class App : MultiDexApplication() {
    override fun onCreate() {
        super.onCreate()
        AppModel.init(this)
    }
}

object AppModel {
    /** 程序是否运行在主线程*/
    var isMainProcess = false

    /** 程序实例*/
    lateinit var app: App
        private set

    /** 初始化调用*/
    fun `init`(app: App) {
        isMainProcess = SystemUtil.isMainProcess(app)
        this.app = app
        /*日志与报错*/
        initLoggerAndErrorHandle(app)
        initData(app)
        //if (!isMainProcess) return
        FC.container(ContainerActivity::class.java)
        /*Toast*/
        T.init(app)
        T.setInterceptor {
            L.d("Toast", it)
            false
        }
        /*权限框架初始化*/
        // 设置不触发错误检测机制
        XXPermissions.setCheckMode(false)
        /*网络请求*/
        Http.init(app)
    }

    /** 初始化数据相关*/
    private fun initData(context: Context) {
        //DH.init(context, MyObjectBox.builder())
        Hawk.init(context)
            //.setLogInterceptor { L.v("Hawk", it) }
            .build()
    }

    /** 日志以及错误崩溃处理初始化*/
    private fun initLoggerAndErrorHandle(context: Context) {
        ANRWatchDog().setANRListener { error ->
            L.e("ANR", error)
            throw error
        }.start()
        L.loggable = SystemUtil.loggable(context)
        L.catchError(errorHandler(context))
    }

    /**错误结果处理与显示*/
    private fun errorHandler(context: Context) = { thread: Thread?, throwable: Throwable ->
        val pid = android.os.Process.myPid()
        if (Hawk.get<Int?>(Values.TAG_ERROR_PID) != pid) {
            val intent = Intent(context, ErrorActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
            Hawk.put(Values.TAG_ERROR_PID, pid)
            val title = if (thread == null) "MainThreadError"
            else "${thread.name}ThreadError"
            val message = throwable.string
            Hawk.put(Values.TAG_ERROR, arrayOf(title, message))
            L.e(title, message)
        }
    }
}